package spring.lottery.common.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import spring.lottery.common.enums.GlobalEnums;
import spring.lottery.common.pojo.ResponseMode;
import spring.lottery.common.util.JWTUtil;
import spring.lottery.common.util.SerializeUtil;


/**
 * 验证登录的时候是否又token
 */
@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录ip: {}  url {}", request.getLocalAddr(), request.getRequestURI());
        String userToken = request.getHeader("user_token");

        Claims claims = JWTUtil.parseToken(userToken);
        if (claims == null) {
            log.error("未登录 {}", request.getPathInfo());

            ResponseMode r = new ResponseMode(GlobalEnums.UNLOGGED.getCode(), "未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(SerializeUtil.encode(r));

            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
